<?php
namespace App\Wen\Utils;

use App\Lib\Uploads\UploadHandler;
use App\Models\WxAttachment;
use Qcloud\Cos\Client;

class FileUtils{

    // 递归删除文件和目录
    public static function deleteFiles($path)
    {
        if (is_file($path)) {
            // 如果是文件，则直接删除
            unlink($path);
        } elseif (is_dir($path)) {
            // 如果是目录，则递归删除目录下的所有文件和子目录
            $files = array_diff(scandir($path), array('.', '..'));

            foreach ($files as $file) {
                self::deleteFiles($path . '/' . $file);
            }
            // 删除空目录
            rmdir($path);
        }
    }

    public static function get_file_temp_url($url){
        if(_empty_($url)){
            return null;
        }
        $arr = self::get_attachment_part_from_url($url);
        if(_empty_($arr)){
            return null;
        }
        $filePath = $arr['path'];

        $cosConfig = Settings::get('cosv5', []);
        $cosClient = new Client(array(
            'region' => $cosConfig['region'],
            'credentials' => array(
                'secretId' => $cosConfig['secretId'],
                'secretKey' => $cosConfig['secretKey'],
            )
        ));
        $temporaryUrl = $cosClient->getObjectUrl($cosConfig['bucket'] . '-' . $cosConfig['appId'], $filePath, '+10 minutes');
        dd($temporaryUrl);
    }

    public static function get_url_attach($url){
        if (_empty_($url)) {
            return null;
        }
        $attachment_part = FileUtils::get_attachment_part_from_url($url);
        if ($attachment_part) {
            $the_attachment = WxAttachment::where([
                ['domain', '=', $attachment_part['domain']],
                ['path', '=', $attachment_part['path']]
            ])->first();

            if ($the_attachment) {
                return $the_attachment;
            }
        }
        return null;
    }

    public static function get_url_attach_id($url){
        if (_empty_($url)) {
            return null;
        }
        $attachment_part = FileUtils::get_attachment_part_from_url($url);
        if ($attachment_part) {
            $the_attachment = WxAttachment::where([
                ['domain', '=', $attachment_part['domain']],
                ['path', '=', $attachment_part['path']]
            ])->first();

            if ($the_attachment) {
                return $the_attachment->id;
            }
        }
        return null;
    }

    public static function force_del_url_file($url)
    {
        if (_empty_($url)) {
            return false;
        }
        $attachment_part = FileUtils::get_attachment_part_from_url($url);
        if ($attachment_part) {
            $the_attachment = WxAttachment::where([
                ['domain', '=', $attachment_part['domain']],
                ['path', '=', $attachment_part['path']]
            ])->first();

            if ($the_attachment) {
                if (UploadHandler::del($the_attachment)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    public static function file_exists($url){
        if (_empty_($url)) {
            return false;
        }
        $attachment_part = FileUtils::get_attachment_part_from_url($url);
        if ($attachment_part) {
            $the_attachment = WxAttachment::where([
                ['domain', '=', $attachment_part['domain']],
                ['path', '=', $attachment_part['path']]
            ])->first();

            if ($the_attachment) {
                return true;
            }
        }
        return false;
    }

    public static function get_attachment_part_from_url($url){
        if(_empty_($url) || strpos($url, 'http') === false){
            return null;
        }
        $url = str_replace('\/', '/', $url);
        $host = parse_url($url, PHP_URL_HOST);
        if(_empty_($host)){
            return null;
        }

        $url_arr = explode($host, $url);

        if(_empty_($url_arr) || !isset($url_arr[0]) || _empty_($url_arr[0]) || !isset($url_arr[1]) || _empty_($url_arr[1])){
            return null;
        }

        return ['domain'=>$url_arr[0] . $host, 'path' => substr($url_arr[1], 1)];

    }

    public static function get_file_extension_from_url($url) {
        // 解析 URL，获取路径部分
        $path = parse_url($url, PHP_URL_PATH);

        // 如果路径为空，返回 null
        if (!$path) {
            return null;
        }

        // 使用 pathinfo 获取文件扩展名
        $extension = pathinfo($path, PATHINFO_EXTENSION);

        // 如果扩展名为空，返回 null
        if (!$extension) {
            return null;
        }

        return $extension;
    }

}
